// ==UserScript==
// @name           Pirates
// @description    autoplayer for the Pirates game
// @namespace      facebook
// @version        2.1.3
// @include        http://apps.facebook.com/piratesrule/*
// @author         blannie
// @contributor	   IEF, colin1497
// ==/UserScript==

var settingsOpen = GM_getValue('settingsOpen', false);
var logOpen = GM_getValue('logOpen', false);
var delay = 10000; //how long to wait between logic loops
var flag = 0; //this flag is used for execution detection.  Setting the flag will prevent further autoplay options from happening during this cycle to ensure the current action completes.
var petvisit = GM_getValue('petvisit', 0); //this will set a petvisit flag every *petvisitfrequency* loads
var petvisitfrequency = 100; //this sets the number of reloads between pet visits, in the future this could be added to the config
var killhealth = 31; // value below which to heal immediately so you don't get killed
var bankgold; //variable to keep gold in bank
var totalgold; //variable to keep total gold in bank and not in bank
var currentTime = new Date();
var lastPlayTime = eval(GM_getValue('lastPlayTime', 0));
var bestProperty = { id:false, roi:0, row:0 };
var nextProperty = GM_getValue('nextProperty', 0);
var reloadTimer;
var logicTimer;
var winCounter = GM_getValue('winCounter', 0);
var lossCounter= GM_getValue('lossCounter', 0);
var SCRIPT = {
	url: 'http://userscripts.org/scripts/source/39741.user.js',
	version: '2.1.3',
	name: 'piratesrule',
	appID: 'app16421175101',
	presentationurl: 'http://userscripts.org/scripts/show/39741'
};

//---------------  Set up a reload timer in case the logic falls down or we get the FB error page
if (GM_getValue('autoClick', '') == "checked" && GM_getValue('paused')==0)
	{
	reload()
	}
// if we haven't played in more than 2X the max reload frequency, reset petvisit.
if ((currentTime-lastPlayTime)>(GM_getValue('r2', 300))*2000)
	{
 	petvisit=0;
	}
// store currentTime as lastPlayTime if we're not paused
if (GM_getValue('paused')==0)
	{
	GM_setValue('lastPlayTime', uneval(currentTime));
	}


var image = '';
var missions = new Array(
// Name , Energy , Tab , Item on tab, form ID, experience

["Count yer ill-gotten treasure",1,1,0,1,1], //1 
["Show around yer crew's wenches",2,1,1,2,2], //2 
["Steal booty from merchants",3,1,2,3,3], //3 
["Break yer Mate out of jail",4,1,3,4,4], //4 
["Beat down another Pirate and pick his pockets",5,1,4,5,5], //5 
["Defend your grog from drunken pirates",6,1,5,6,7], //6

["Storm the town merchants",5,2,0,7,6], //7 
["Recover treasure from a sunken vessel",4,2,1,8,5], // 8 
["Row into town and take what you can!",7,2,2,9,9], //9 
["Ambush a band of sleeping scallywags",10,2,3,10,13], //10 
["Travel the seas in search of loot",15,2,4,11,20], //11 
["Fight off a raiding party",18,2,5,32,24], //32

["Go into town and party with yer wenches then take their gold",12,3,0,12,16], //12 
["Disguise yer crew as merchants and plunder",17,3,1,13,23], //13 
["Cause chaos on the High Seas",18,3,2,14,25], //14 
["Plunder the Wine & Brandy vessels",10,3,3,15,14], //15 
["Rifle through the wreckage of the Black Vessel",15,3,4,16,21], //16 
["Raid the port town",25,3,5,17,28], //17 
["Plunder the Sea Nymph & take their loot",20,3,6,18,35], //18

["Teach a mutinous crew member a lesson",12,4,0,19,17], //19 
["Drink and Sing, Yo Ho Ho, a Pirate's life for me",26,4,1,20,37], //20 
["Fight the one-legged Captain Jim",28,4,2,21,40], //21 
["Fight the Black Vessel & take prisoners",30,4,3,22,43], //22 
["Steal from yer crew's booty while they are sleeping",16,4,4,23,23], //23 
["Battle Blackbeard and claim his treasure",18,4,5,24,26], //24

["Party with yer wenches and take their gold",20,5,0,25,29], //25 
["Ambush the town's local Red Soldiers",31,5,1,26,45], //26 
["Follow the Phantom Vessel and attack from afar",30,5,2,27,44], //27 
["Travel in search of the Phantom Treasure",40,5,3,28,59], //28 
["Pistol duel with Captain Black Beard",25,5,4,29,37], //29 
["Get into the duel of the Ages with Davey Jones",33,5,5,30,49], //30

["Roll the bones",10,6,0,33,15], //33
["Shave Moustache Moe while he sleeps",20,6,1,34,30], 
["Defend your honor against a rival crew",30,6,2,35,45], 
["Sink a privateer vessel",40,6,3,36,60], 
["Seek a nearby volcano",50,6,4,37,75], 
["Hail the beacon of the Flying Dutchman",56,6,5,38,84], 
["Fight the Plague Crew of the Flying Dutchman",66,6,6,39,99], //39

["Swing Aboard an Enemy Ship",30,7,0,40,46], //40
["Sword fight in the rigging",47,7,1,41,73], 
["Run a warship through a reef",63,7,2,42,98], 
["Make the prisoners walk the plank",70,7,3,43,109], 
["Give an approaching ship a 'real' 21 gun salute",74,7,4,44,116], 
["Sail through rocky, shark infested waters",80,7,5,45,126], 
["Avoid Charybdis",100,7,6,46,156], //46

["Sing a shanty with your crew across ships",40,8,0,47,62], //47
["Snipe an enemy ship from the crow's nest",25,8,1,48,39], //48
["Ram the side of a smaller vessel",52,8,2,49,82], //49
["Ambush a ship by raising their nation's flag",30,8,3,50,48], //50
["Chum the water and let the sharks finish 'em off",23,8,4,51,37], //51
["Follow the Sirens' song",31,8,5,52,51], //52
["Seduce the merfolk",60,8,6,53,100], //53

["Run some stolen rum into Port Royale",35,9,0,54,58],
["Bring wenches back for the crew",66,9,1,58,110],
["Put some heat on the local blacksmith",56,9,2,56,93],
["Kill the Mayor's personal guards",90,9,3,61,151],
["Raid a powder house and blow it up",50,9,4,55,83],
["Free the slaves and make em join yer crew",64,9,5,60,107],
["Undercut the Mayor of Port Royal's tobacco trade",70,9,6,59,117],
["Defend the port against buccaneers",48,9,7,57,80]
);

var missionsbyexp = missions;

var missionTabs = new Array(
["Scallywag (Levels 1-4)"],
["Swashbuckler (Levels 5-8)"],
["Scurvy Dog (Levels 9-14)"],
["Deck Hand (Levels 15-25)"],
["Pirate (Levels 26-38)"],
["First Mate (Levels 39-53)"],
["Captain (Levels 54-69)"],
["Commander (Levels 70-87)"],
["Commodore (Levels 88+)"]
);

var curTabMastery = new Array();
var fightUsers = new Array();
var fightDeadmeat= new Array(); //People I can win against
var fightToomuch = new Array(); //People who have beaten me

var XMLHttpFactories = [
    function () {return new XMLHttpRequest()},
    function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

document.getElementsByXPath = function(sValue){ var aResult = new Array();var a = this.evaluate(sValue, ((arguments.lenth > 1) ? arguments[1] : this), null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);for ( var i = 0 ; i < a.snapshotLength ; i++ ){aResult.push(a.snapshotItem(i));}return aResult;};

//Get absolute banner position
bannerTop =   getPositionTop(document.getElementById(SCRIPT.appID+'_banner_row')); //140
bannerLeft =  getPositionLeft(document.getElementById(SCRIPT.appID+'_banner_row')); // 300
var pauseButton = document.createElement("div");

// ---------------------------- Get parsed global variables ------------------//
var alliance= document.body.innerHTML.substring(document.body.innerHTML.indexOf('Crew')+57);
alliance = alliance.substring(0,alliance.indexOf(')'));
alliance =  parseInt(alliance);
var gold =  document.getElementsByXPath("//span[contains(@class,'stats_info_box')]")[0].innerHTML.split('>')[1];
	gold = parseInt(gold.replace(/,/g, ''));
var health = parseInt(document.getElementById(SCRIPT.appID+'_current_health').innerHTML);
var maxenergy = document.getElementById(SCRIPT.appID+'_current_energy').parentNode.innerHTML.substring(document.getElementById(SCRIPT.appID+'_current_energy').parentNode.innerHTML.indexOf(">/")+2);
var maxStamina = document.getElementById(SCRIPT.appID+'_current_stamina').parentNode.innerHTML.substring(document.getElementById(SCRIPT.appID+'_current_stamina').parentNode.innerHTML.indexOf(">/")+2);
var energy = parseInt(document.getElementById( SCRIPT.appID+'_current_energy').innerHTML);
var stamina = parseInt(document.getElementById( SCRIPT.appID+'_current_stamina').innerHTML);
var experience = document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.substring(0,document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.indexOf("/"));
var nextlevelexperience = document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.substring(document.getElementById(SCRIPT.appID+'_stats_table').childNodes[1].childNodes[0].childNodes[9].childNodes[1].childNodes[3].innerHTML.indexOf("/")+1);
var experiencetolevel= nextlevelexperience - experience;


// ---------------------------- menu global variables ------------------------------------//

var settingsButton
var viewLogButton
var clrLogButton
var settingsBox
var logBox
var versionBox
var autoClick
var refreshTimes
var autoProperty
var autoMission
var missionMastery 
var selectMission
var choiceTab
var choice
var autoBank
var bankConfig
var bankKeep
var autoHeal
var healthLevel
var healthRage
var updateButton
var autoFight
var fightMinimum
var fightRandom
var fightLevel
var fightClanSize
var freshMeat
var fightList
var autoTreasure
var autoPet
var autoStats
var statAtt
var statDef
var statEnergy
var statHP
var statStrength
var autoIsland
var saveButton
var saveNotification
var buyCrewProperty
   


//Grab the last known request form ID
var reqID = GM_getValue('reqformID',false);

//If we don't have a reqID or its older than a day, grab a fresh one.
if (!reqID)
{
	if (location.href.indexOf(SCRIPT.name+'/recruit') != -1)
	{
		Array.forEach(document.getElementsByTagName("input"),
			function(obj)
			{
				if (obj.id.indexOf('mfs_typeahead_req_form_') != -1)
				{
					GM_setValue('reqformID',obj.id.replace('mfs_typeahead_req_form_',''));
					return;
				}
			}
		);
	}
	else
		window.location = "http://apps.facebook.com/"+SCRIPT.name+"/recruit.php";
	return;
}

/*
var members = document.getElementsByXPath("//a[contains(@href,'/"+SCRIPT.name+"/stats.php?user=')]");
//First link is always yourself from the 'my stats' link at the top
 Array.forEach(members,
	 function(member){
		var mobid = member.href.match(/\d+$/);
		var newImg = document.createElement("img");
		newImg.setAttribute("src", image);
		newImg.addEventListener('click',invitePlayer(mobid), false);
		member.parentNode.insertBefore(newImg,member);
	 }
	 );
*/
	 




//***********************************************************
//-------------Logic here runs every page reload--------------
//***********************************************************

// --------------  Call the pause/unpause setup function ----------------//
pause()
// --------------  Build the configuration and log windows --------//
buildmenus()
// --------------  Parse whatever window we're on and log ---------//
parseandlog()
// --------------  Scan the fight list any time we happen to be on the fight page
if (GM_getValue('fightUsers', '') != '')
	{
	fightUsers=eval(GM_getValue('fightUsers', ''));
	}
if (location.href.indexOf(SCRIPT.name+'/fight') != -1)
	{
	scanfightlist()
	}
// --------------  If we're on the properties page, put data on the screen
if (location.href.indexOf(SCRIPT.name+'/properties') != -1)
	{
	propertydata()
	}
//---------------  Decrement petvisit every load
petvisit = petvisit - 1
if (petvisit < 0)
	{
	petvisit = 0;
	}
//---------------  Store pet visit value for next page load
GM_setValue('petvisit', petvisit);
//---------------  Check if paused, if not, run autoplay logic loop
if (GM_getValue('paused')==0)
	{
//	while (flag == 0)
//		{
			logicTimer=window.setTimeout(logic, 3000);
//		}
	}
